<template>
  <div class="add">
    <el-card class="add-container">
      <el-form
        :model="articleForm"
        :rules="rules"
        ref="articleRef"
        label-width="100px"
        class="articleForm"
      >
        <el-form-item label="文章标识符" prop="publish_id">
          <el-input
            style="width: 300px"
            v-model="articleForm.publish_id"
            placeholder="请输入文章标识符"
          ></el-input>
        </el-form-item>
        <el-form-item label="文章分类">
          <el-select placeholder="分类" v-model="articleForm.list">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="文章标题" prop="title">
          <el-input
            style="width: 300px"
            v-model="articleForm.title"
            placeholder="请输入文章标题"
          ></el-input>
        </el-form-item>
        <el-form-item label="文章简介" prop="intro">
          <el-input
            style="width: 300px"
            type="textarea"
            v-model="articleForm.intro"
            placeholder="请输入文章简介(100字)"
          ></el-input>
        </el-form-item>
        <el-form-item label="文章标签" prop="tag">
          <el-input
            style="width: 300px"
            v-model="articleForm.tag"
            placeholder="请输入文章小标签"
          ></el-input>
        </el-form-item>
        <el-form-item label="上架状态" prop="sellStatus">
          <el-radio-group v-model="articleForm.sellStatus">
            <el-radio label="0">上架</el-radio>
            <el-radio label="1">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="文章主图" prop="coverImg">
          <el-upload
            ref="pictureUpload"
            name="banner"
            class="avatar-uploader"
            accept="jpg,jpeg,png"
            list-type="picture-card"
            action="http://localhost:3333/web_question/admin/upload"
            :limit="1"
            :auto-upload="true"
            :before-upload="handleBeforeUpload"
            :on-success="handleUrlSuccess"
            :on-change="handleChange"
          >
            <el-icon><Plus /></el-icon>
            <template #file="{ file }">
              <div>
                <img
                  class="el-upload-list__item-thumbnail"
                  :src="file.url"
                  alt=""
                />
                <span class="el-upload-list__item-actions">
                  <span
                    class="el-upload-list__item-delete"
                    @click="handleRemove(file)"
                  >
                    <el-icon><Delete /></el-icon>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="详情内容">
          <!-- <div ref="editor"></div> -->
          <Editor @changeContext="getContext" />
        </el-form-item>
        <el-form-item>
          <!--  id ? "立即修改" : "立即创建" -->
          <el-button type="primary" @click="submitForm">{{
            "立即发布"
          }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>
<script setup>
import { reactive, ref, toRefs, getCurrentInstance, onMounted } from "vue";
import Editor from "../components/Editor.vue";
import { postPublish } from "../../api/publish";

const { proxy } = getCurrentInstance();

const pictureUpload = ref(null);

const state = reactive({
  //   uploadImgServer,
  //   token: localGet("token") || "",
  //   id: id,
  defaultCate: "",
  articleForm: {
    publish_id: "",
    list: "",
    title: "",
    intro: "",
    tag: "",
    sellStatus: "0",
    coverImg: "",
    context: "",
  },
  rules: {
    // title: [
    //   { required: "true", message: "请填写文章标题", trigger: ["change"] },
    // ],
    // coverImg: [
    //   { required: "true", message: "请上传文章主图", trigger: ["change"] },
    // ],
  },
  categoryId: "",
  options: [
    {
      value: "html",
      label: "html",
    },
    {
      value: "css",
      label: "css",
    },
    {
      value: "javascript",
      label: "javascript",
    },
  ],
});
// 暴露 reactive响应式数据
const { defaultCate, articleForm, rules, options, categoryId } = toRefs(state);

const handleBeforeUpload = (file) => {
  const sufix = file.name.split(".")[1] || "";
  if (!["jpg", "jpeg", "png"].includes(sufix)) {
    ElMessage.error("请上传 jpg、jpeg、png 格式的图片");
    return false;
  }
};

// 上传图片拿到图片的名称
const handleChange = (file) => {
  // console.log(file);
  state.articleForm.coverImg = file.name;
};

// 上传图片
const handleUrlSuccess = (val) => {
  console.log("上传图片", val);
  // state.articleForm.url = val.data || "";
};

// 移除上传的图片
const handleRemove = (file) => {
  pictureUpload.value.handleRemove(file);
};

// 获取富文本的内容
const getContext = (context) => {
  // console.log("获取富文本的内容", context);
  state.articleForm.context = context;
};

// 发布文章
const submitForm = () => {
  // console.log(state.articleForm);
  postPublish(proxy, state.articleForm).then((data) => {
    if (data.code === 200) {
      // 提示
      ElMessage({
        type: "success",
        message: "发布文章成功",
      });
      // 发布成功后清空表单
      state.articleForm = {
        publish_id: "",
        list: "",
        title: "",
        intro: "",
        tag: "",
        sellStatus: "0",
        coverImg: "",
        context: "",
      };
    } else {
      console.log("错误：", data);
      // 提示
      ElMessage({
        type: "error",
        message: "发布文章失败",
      });
    }
  });
};

// 使用富文本 wangEditor
// const editor = ref(null);
// let instance;
onMounted(() => {
  // instance = new WangEditor(editor.value);
  // instance.config.showLinkImg = false;
  // instance.config.showLinkImgAlt = false;
  // instance.config.showLinkImgHref = false;
  // instance.config.uploadImgMaxSize = 2 * 1024 * 1024; // 2M
  // instance.config.uploadFileName = "file";
  //   instance.config.uploadImgHeaders = {
  //     token: state.token,
  //   };
  // 图片返回格式不同，需要自定义返回格式
  // instance.config.uploadImgHooks = {
  // 图片上传并返回了结果，想要自己把图片插入到编辑器中
  // 例如服务器端返回的不是 { errno: 0, data: [...] } 这种格式，可使用 customInsert
  // customInsert: function (insertImgFn, result) {
  //   console.log("result", result);
  // result 即服务端返回的接口
  // insertImgFn 可把图片插入到编辑器，传入图片 src ，执行函数即可
  //     if (result.data && result.data.length) {
  //       result.data.forEach((item) => insertImgFn(item));
  //     }
  //   },
  // };
  //   instance.config.uploadImgServer = uploadImgsServer;
  // Object.assign(instance.config, {
  //   onchange() {
  //     console.log("change");
  //   },
  // });
  // instance.create();
  //   if (id) {
  //     axios.get(`/goods/${id}`).then((res) => {
  //       const { goods, firstCategory, secondCategory, thirdCategory } = res;
  //       state.goodForm = {
  //         goodsName: goods.goodsName,
  //         goodsIntro: goods.goodsIntro,
  //         originalPrice: goods.originalPrice,
  //         sellingPrice: goods.sellingPrice,
  //         stockNum: goods.stockNum,
  //         goodsSellStatus: String(goods.goodsSellStatus),
  //         goodsCoverImg: proxy.$filters.prefix(goods.goodsCoverImg),
  //         tag: goods.tag,
  //         categoryId: goods.goodsCategoryId,
  //       };
  //       state.categoryId = goods.goodsCategoryId;
  //       state.defaultCate = `${firstCategory.categoryName}/${secondCategory.categoryName}/${thirdCategory.categoryName}`;
  //       if (instance) {
  //         // 初始化商品详情 html
  //         instance.txt.html(goods.goodsDetailContent);
  //       }
  //     });
  //   }
});
</script>

<style scoped>
.add {
  display: flex;
}
.add-container {
  flex: 1;
  height: 100%;
}
.avatar-uploader {
  width: 100px;
  height: 100px;
  color: #ddd;
  font-size: 30px;
}
.avatar-uploader-icon {
  display: block;
  width: 100%;
  height: 100%;
  border: 1px solid #e9e9e9;
  padding: 32px 17px;
}
</style>
